using System;
using System.Collections;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Unity.Mathematics;
using UnityEngine;

public class WebSocketClient
{
    static private ClientWebSocket websocket = new ClientWebSocket();

    async public static void Say(string message = "unblock")
    {
        try
        {
            // 连接到本地的WebSocket服务器
            if (websocket.State == WebSocketState.Open) websocket.Dispose();
            websocket = new ClientWebSocket();
            Debug.Log("WebSocketClient Starting");
            await websocket.ConnectAsync(new Uri("ws://localhost:3002"), CancellationToken.None);
            Debug.Log("WebSocketClient connected!");

            ArraySegment<byte> bytesToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(""+message));
            await websocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
            Debug.Log("Sent "+message+" message to server.");

            // 关闭连接
            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            Debug.Log("WebSocket connection closed.");
            websocket.Dispose();
        }
        catch (Exception ex)
        {
            Debug.Log("WebSocket exception: " + ex.Message); 
            websocket.Dispose();
        }
    }



}
